package com.sysmanage.etl.controls;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sysmanage.etl.model.ETL_DataSource;
import com.sysmanage.etl.model.ETL_Property;
import com.sysmanage.etl.model.ETL_Table;
import com.sysmanage.etl.service.IDataSourceService;
import com.sysmanage.etl.service.IPropertyService;
import com.sysmanage.etl.utils.JdbcUtils;
import com.sysmanage.etl.utils.PropertyUtils;
import com.sysmanage.etl.utils.StringUtils;
import com.sysmanage.etl.vo.PropertyFullVO;
import com.sysmanage.etl.vo.Tree;
import com.sysmanage.framework.controls.struts2.BaseTg;

@Scope("prototype")
@Controller(value = "dataSourceTg")
public class DataSourceTg extends BaseTg {
	private static final long serialVersionUID = 7526673934864721816L;
	private Map<String, Object> result = new HashMap<String, Object>();;
	private ETL_DataSource ds;
	private int total;
	private String attributes;
	private Integer treeId;
	private Integer dataSourceId;
	
	@Resource
	private IDataSourceService dataSourceService;
	@Resource
	private IPropertyService propertyService;
	
	public String index() {
		return "index";
	}
	public String table() {
		return "table";
	}
	public String property() {
		return "property";
	}

	public void save() {
		try {
			result = new HashMap<String, Object>();
			String dbName = ds.getDataSource_name();
			ETL_DataSource dataSource = dataSourceService.find("from ETL_DataSource where dataSource_name = '"+dbName+"'");
			if(dataSource != null){
				result.put("success", false);
				result.put("message", "已存在相同名称的数据源,请重新输入名称!");
			}else{
				dataSourceService.saveDataSource(ds);
				result.put("success", true);
				result.put("message", "新增目标数据源成功");
			}
			JSONObject json = JSONObject.fromObject(result);
			this.outJsonPlainString(response, json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("message", "数据错误,请仔细检查数据后再提交");
			JSONObject json = JSONObject.fromObject(result);
			this.outJsonPlainString(response, json.toString());
		}
	}
	
	/**
	 * 
	 * 重新加载数据源表
	 * 
	 * TODO 重新加载数据源表 ---方法已写好，还未添加到页面
	 */
	public void reloadTable() {
		ETL_DataSource dataSource = dataSourceService.findById(dataSourceId);
		if (dataSource != null) {
			List<ETL_Table> tables = PropertyUtils.getETL_Tables(dataSource);
			dataSourceService.reloadTable(dataSource, tables);
		}
		result.put("success", true);
		result.put("message", "重新加载数据源成功");
		JSONObject json = JSONObject.fromObject(result);
		this.outJsonPlainString(response, json.toString());
	}

	public void checkConnection() {
		result = new HashMap<String, Object>();
		result.put("success", JdbcUtils.check(ds));
		JSONObject json = JSONObject.fromObject(result);
		this.outJsonString(response, json.toString());
	}
	
	public void update() {
		result = new HashMap<String, Object>();
		result.put("success", true);
		result.put("message", "修改目标数据源成功");
		dataSourceService.updateDataSource(ds);
		JSONObject json = JSONObject.fromObject(result);
		this.outJsonPlainString(response, json.toString());
	}

	public void delete() {
		result = new HashMap<String, Object>();
		result.put("success", true);
		result.put("message", "删除目标数据源成功!");
		try {
			dataSourceService.deleteDataSource(ds.getDataSource_id());
		} catch (Exception e) {
			result.put("success", false);
			result.put("message", "删除目标数据源失败,请先删除其他相关配置!");
		}
		JSONObject json = JSONObject.fromObject(result);
		this.outJsonPlainString(response, json.toString());
	}

	public void listAll() {
		//Tree 类型为datasource时 返回空
		if("table".equalsIgnoreCase(this.attributes)) {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setIgnoreDefaultExcludes(false);
			jsonConfig.setExcludes(new String[] { "tables" , "propertys" });
			
			List<ETL_Property> list = propertyService.findList("from ETL_Property where table.table_id=" + treeId , page , rows);
			this.total = propertyService.findCountBySql("from ETL_Property where table.table_id=" + treeId );
					
			List<PropertyFullVO> listVO = new ArrayList<PropertyFullVO>(list.size());
			for(ETL_Property property : list){
				PropertyFullVO vo = new PropertyFullVO();
				BeanUtils.copyProperties(property, vo);
				vo.setTable_name(property.getTable().getTable_name());
				listVO.add(vo);
			}
			JSONArray jsonArray = JSONArray.fromObject(listVO , jsonConfig);
			String baseStr = "{\"total\":" + this.total + ",\"rows\":";
			baseStr = baseStr + jsonArray.toString() + "}";
			this.outJsonString(response, baseStr);
		} else {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setIgnoreDefaultExcludes(false);
			jsonConfig.setExcludes(new String[] { "tables" , "propertys" });
			
			Collection<ETL_DataSource> list = dataSourceService.findList("from ETL_DataSource");
			this.total = list.size();
			JSONArray jsonArray = JSONArray.fromObject(list , jsonConfig);
			String baseStr = "{\"total\":" + this.total + ",\"rows\":";
			baseStr = baseStr + jsonArray.toString() + "}";
			this.outJsonString(response, baseStr);
		}

	}

	/**
	 * 获取
	 * 
	 * @return
	 */
	public void loadTree() {
		Collection<ETL_DataSource> list = dataSourceService.findList("from ETL_DataSource");
		List<Tree> result = new ArrayList<Tree>();
		for (ETL_DataSource dataSource : list) {
			Tree dsTree = new Tree();
			dsTree.setId(dataSource.getDataSource_id());
			dsTree.setText(dataSource.getDataSource_name());
			dsTree.setAttributes("dataSource");
			List<Tree> children = new ArrayList<Tree>();

			Set<ETL_Table> tables = dataSource.getTables();
			for (ETL_Table table : tables) {
				if(table.getDisplay() != null && table.getDisplay() ){
					Tree tbTreee = new Tree();
					tbTreee.setId(table.getTable_id());
					tbTreee.setText(StringUtils.isBlank(table.getTable_alais()) ? table.getTable_name() : table.getTable_alais() + "(" + table.getTable_name() + ")");
					tbTreee.setAttributes("table");
					children.add(tbTreee);
				}
			}
			dsTree.setChildren(children);
			result.add(dsTree);
		}
		JSONArray jsonArray = JSONArray.fromObject(result);
		this.outJsonString(response, jsonArray.toString());
	}

	
	
	public void setTreeId(Integer treeId) {
		this.treeId = treeId;
	}

	public void setAttributes(String attributes) {
		this.attributes = attributes;
	}

	public ETL_DataSource getDs() {
		return ds;
	}

	public void setDs(ETL_DataSource ds) {
		this.ds = ds;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}
	

	public int getTotal() {
		return this.total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
	public void setDataSourceId(Integer dataSourceId) {
		this.dataSourceId = dataSourceId;
	}

}
